// pages/detail-song/detail-song.js
import recommendStore from "../../store/recommendStore"
import rankingStore from "../../store/rankingStore"
import {
  getPlayListDetail
} from "../../services/music"
import playerStore from "../../store/playerStore"

Page({
  data: {
    type: "ranking",
    key: "newRanking",
    id: "",

    songInfo: []
  },
  onLoad() {
    // 确定获取数据的类型
    const type = this.options.type
    this.setData({
      type
    })

    //获取store中榜单数据
    if (type === "ranking") {
      const key = this.options.key
      this.data.key = key
      rankingStore.onState(key, this.handleRanking)
    } else if (type === "recommend") {
      recommendStore.onState("recommendSongInfo", this.handleRanking)
    } else if (type === "menu") {
      const id = this.options.id
      this.data.id = id
      this.fetchMenuSongInfo()
    }
  },

  async fetchMenuSongInfo() {
    const res = await getPlayListDetail(this.data.id)
    this.setData({
      songInfo: res.playlist
    })
  },

  //事件监听
  onSongItemTap() {
    playerStore.setState("playSongList", this.data.songInfo.tracks)
  },

  //store共享数据
  handleRanking(value) {
    this.setData({
      songInfo: value
    })
    wx.setNavigationBarTitle({
      title: value.name,
    })
  },

  onUnload() {
    if (this.data.type === "ranking") {
      rankingStore.offState(this.data.key, this.handleRanking)
    } else if (this.data.type === "recommend") {
      recommendStore.offState("recommendSongInfo", this.handleRanking)
    }

  }
})